import socket
import urllib.request, urllib.parse, urllib.error
import http.cookiejar

url = 'http://test.jdzschina.com/pm'
login_url = 'http://test.jdzschina.com/login.php?action=login'

def build_http():
  socket.setdefaulttimeout(10)
  opener = urllib.request.build_opener()
  cj = http.cookiejar.CookieJar()
  opener.add_handler(urllib.request.HTTPCookieProcessor(cj))

  opener.addheaders = [('User-Agent', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko)\
      Chrome/34.0.1847.116'),
                                    ('Connection', 'keep-alive'),
                                    ('Cache-Control', 'no-cache'),
                                    ('Accept-Language', 'zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3'),
                                    ('Accept-Encoding', 'gzip, deflate'),
                                    ('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8')]
  urllib.request.install_opener(opener)

def login(login_url, params):
  '''返回登陆后的cookie值'''
  params = urllib.parse.urlencode(params);
  req = urllib.request.Request(login_url, params.encode('utf8'))
  response = urllib.request.urlopen(req)

  cookie = []
  for k, v in response.info().items():
    if k == 'Set-Cookie':
      cookie.append(v)

  return (';'.join(cookie))

def get(url, cookie=None):
  req = urllib.request.Request(url)
  if cookie:
    req.add_header('Cookie', cookie)

  resp = urllib.request.urlopen(req)

  # print(dir(req))
  # print(req.headers)
  # print(req.get_data())

  # print(dir(resp))
  # print(resp.info())
  # print(resp.status)

  print(resp.read().decode('utf8', 'ignore'))

def get2(url):
  build_http()  #记住cookie, 在登录后访问其他页面时携带cookie
  login(login_url, {'gmtusername':'caigoutest', 'gmtpassword':'caigoutest'})
  get(url)

def get3(url):
  params={'gmtusername':'caigoutest', 'gmtpassword':'caigoutest'}
  cookie = login(login_url, params)
  get(url, cookie)

if __name__ == '__main__':
  get3(url)
